package stru1.day9;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 20. 有效的括号
 */
public class Solution1 {
    public static void main(String[] args) {
        System.out.println(isValid("()"));
        System.out.println(isValid("()[]{}"));
        System.out.println(isValid("(]"));
        System.out.println(isValid("([)]"));
        System.out.println(isValid("{[]}"));
    }

    /**
     * 利用栈来配对符号，(栈的经典应用)
     */
    public static boolean isValid(String s) {
        char[] chars = s.toCharArray();
        Deque<Character> stack = new ArrayDeque<>();
        for (char aChar : chars) {
            switch (aChar) {
                case '(':
                case '[':
                case '{':
                    stack.push(aChar);
                    break;
                case ')':
                    if (stack.isEmpty() || '(' != stack.pop()) return false;
                    break;
                case ']':
                    if (stack.isEmpty() || '[' != stack.pop()) return false;
                    break;
                case '}':
                    if (stack.isEmpty() || '{' != stack.pop()) return false;
                    break;
            }
        }
        return stack.isEmpty();
    }
}
